package com.zy.project2_aop_base.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: mavenTest153
 * @description: 相当于jdk动态代理的增强类
 * @author: zy
 * @create: 2025-07-16 09:00
 */
public class MyInterceptor implements MethodInterceptor {

    private Object target;  //目标对象

    public MyInterceptor(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        //前置增强
        if(  method.getName().startsWith("update")|| method.getName().startsWith("save") ){  // @Pointcut("execution(* com.zy.project1.biz.*.find*(..))")
            //@Before
            checkRight();
        }
        //调用目标方法
        Object returnValue=method.invoke(target,args);


        if(  method.getName().startsWith("show")|| method.getName().startsWith("find") ){  // @Pointcut("execution(* com.zy.project1.biz.*.find*(..))")
            //后置增强
            //@After
            log();
        }


        return returnValue;
    }


    public void checkRight(){
        System.out.println("权限验证...");
    }

    public void log(){
        System.out.println("记录日志...");
    }
}
